@file:Suppress("UNUSED_PARAMETER")

package cn.android666.recorddemowithnoise

import android.content.Context
import android.content.Intent
import android.media.AudioManager
import android.os.Build
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import cn.android666.recorddemowithnoise.databinding.ActivityMainBinding

fun printLog(message: String) = Log.i(MainActivity::class.java.simpleName, message)

class MainActivity : AppCompatActivity() {

    private val binding by lazy { ActivityMainBinding.inflate(layoutInflater) }
    private val pcmPlayer by lazy { PcmPlayer() }
    private val audioRecorder by lazy { AudioRecorder() }
    private var voiceCallServiceIntent: Intent? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(binding.root)

        // 启动前台服务
        startVoiceCallService()

        // 告诉系统，当按音量键时，调整的是哪个音频流的音量，如果不设置默认调整的是音乐流的声音大小
        volumeControlStream = STREAM_TYPE

        val audioManager = App.app.getSystemService(Context.AUDIO_SERVICE) as AudioManager
        val musicMaxVolume = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC)
        val voiceCallMaxVolume = audioManager.getStreamMaxVolume(AudioManager.STREAM_VOICE_CALL)
        printLog("musicMaxVolume: $musicMaxVolume")
        printLog("voiceCallMaxVolume: $voiceCallMaxVolume")

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
            val musicMinVolume = audioManager.getStreamMinVolume(AudioManager.STREAM_MUSIC)
            val voiceCallMinVolume = audioManager.getStreamMinVolume(AudioManager.STREAM_VOICE_CALL)
            printLog("musicMinVolume: $musicMinVolume")
            printLog("voiceCallMinVolume: $voiceCallMinVolume")
        }

        // 申请录音权限和存储权限
        PermissionUtil.registerForActivityResult(this)
        PermissionUtil.requestPermission(this) { printLog("申请到录音和存储权限了^_^") }

        binding.volumeUp.setOnClickListener {
            /*val audioManager = App.app.getSystemService(AUDIO_SERVICE) as AudioManager
            val maxVolume = audioManager.getStreamMaxVolume(STREAM_TYPE)
            val minVolume = if (STREAM_TYPE == AudioManager.STREAM_VOICE_CALL) 1 else 0
            var currentVolume = audioManager.getStreamVolume(STREAM_TYPE)
            val newVolume = if (currentVolume >= maxVolume) maxVolume else currentVolume + 1
            audioManager.setStreamVolume(STREAM_TYPE, newVolume, 1)// 通话类型音量范围：1 ~ 7，音乐类型：0 ~ 15
            currentVolume = audioManager.getStreamVolume(STREAM_TYPE)
            binding.volumeInfo.text = "当前声音类型：${if (STREAM_TYPE == AudioManager.STREAM_VOICE_CALL) "STREAM_VOICE_CALL" else "STREAM_MUSIC"}\n音量范围：${minVolume} - ${maxVolume}\n当前音量大小：$currentVolume"*/
            pcmPlayer.volumeUp()
        }

        binding.volumeDown.setOnClickListener {
            /*val audioManager = App.app.getSystemService(AUDIO_SERVICE) as AudioManager
            val maxVolume = audioManager.getStreamMaxVolume(STREAM_TYPE)
            val minVolume = if (STREAM_TYPE == AudioManager.STREAM_VOICE_CALL) 1 else 0
            var currentVolume = audioManager.getStreamVolume(STREAM_TYPE)
            val newVolume = if (currentVolume <= minVolume) minVolume else currentVolume - 1
            audioManager.setStreamVolume(STREAM_TYPE, newVolume, 1)// 通话类型音量范围：1 ~ 7，音乐类型：0 ~ 15
            currentVolume = audioManager.getStreamVolume(STREAM_TYPE)
            binding.volumeInfo.text = "当前声音类型：${if (STREAM_TYPE == AudioManager.STREAM_VOICE_CALL) "STREAM_VOICE_CALL" else "STREAM_MUSIC"}\n音量范围：${minVolume} - ${maxVolume}\n当前音量大小：$currentVolume"*/
            pcmPlayer.volumeDown()
        }

        binding.playWhiteNoise.setOnLongClickListener {
            showSingleChoiceDialog()
            true
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        // 停止前台服务
        stopVoiceCallService()
    }

    private val items = arrayOf("音量加0dB", "音量加5dB", "音量加10dB", "音量加15dB", "音量加20dB", "音量加25dB", "音量加30dB")
    private var currentSelect = 3

    private fun showSingleChoiceDialog() {
        AlertDialog.Builder(this)
            .setTitle("请选择一个选项")
            .setSingleChoiceItems(items, currentSelect) { dialog, which ->
                // 当用户选择某个选项时更新选中项
                currentSelect = which
            }
            .setPositiveButton("确定") { dialog, which ->
                // 用户点击确定后获取选中的项
                val selectedItem = items[currentSelect]
                Toast.makeText(this, "你选择了: $selectedItem", Toast.LENGTH_SHORT).show()
                pcmPlayer.startPlay(true, currentSelect)
            }
            .create()
            .show()
    }

    // 启动前台服务
    private fun startVoiceCallService() {
        voiceCallServiceIntent = Intent(this, VoiceCallService::class.java)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            startForegroundService(voiceCallServiceIntent)
        } else {
            startService(voiceCallServiceIntent)
        }
    }

    // 停止前台服务
    private fun stopVoiceCallService() {
        voiceCallServiceIntent?.let {
            stopService(it)
        }
    }

    fun startRecord(view: View) { audioRecorder.startRecord()}// 开始录音
    fun stopRecord(view: View) { audioRecorder.stopRecord(); pcmPlayer.stopPlay() } // 停止录音
    fun playWhiteNoise(view: View) { pcmPlayer.startPlay(true, currentSelect) }       // 播放PCM噪
    fun playBaiYang(view: View) { pcmPlayer.startPlay(false) }       // 播放PCM噪
    fun stopPlay(view: View) { pcmPlayer.stopPlay() }        // 停止播放
    fun openSpeaker(view: View) { Speakerphone.on() }         // 开扬声器
    fun closeSpeaker(view: View) { Speakerphone.off() }       // 关扬声器

}